package com.leenmvc.core.security.service;

import com.google.code.kaptcha.Producer;
import com.leenmvc.core.base.BaseService;
import com.leenmvc.core.exception.BusinessException;
import com.leenmvc.core.security.dao.core.SysCaptchaDao;
import com.leenmvc.core.security.dao.core.SysUserDao;
import com.leenmvc.core.security.entity.core.SysCaptcha;
import com.leenmvc.core.security.entity.core.SysUser;
import com.leenmvc.core.utils.security.PasswordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;

/**
 * 登录服务
 */
@Service
public class LoginService extends BaseService<SysUser> {

    @Autowired
    private Producer producer;

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private SysCaptchaDao sysCapchaDao;

    /**
     * 创建验证码
     *
     * @param uuid
     * @return
     */
    public BufferedImage create(String uuid) {
        // 生成文字验证码
        String code = producer.createText();
        // 保存到缓存
        SysCaptcha sysCaptcha = new SysCaptcha();
        sysCaptcha.setUuid(uuid);
        sysCaptcha.setCode(code);
        boolean success = sysCapchaDao.saveOrUpdate(sysCaptcha);
        if(success) {
            return producer.createImage(code);
        }
        throw new BusinessException("创建验证码失败！");
    }

    /**
     * 仅用于测试
     *
     * @param uuid
     * @return
     */
    public SysCaptcha createTestCaptcha(String uuid) {
        // 生成文字验证码
        String code = producer.createText();
        // 保存到缓存
        SysCaptcha sysCaptcha = new SysCaptcha();
        sysCaptcha.setUuid(uuid);
        sysCaptcha.setCode(code);
        if(sysCapchaDao.saveOrUpdate(sysCaptcha)) {
            return sysCaptcha;
        }
        throw new BusinessException("创建验证码失败！");
    }

    /**
     * 修改密码
     * @param number  手机号或邮箱号
     * @param type    1手机号2邮箱
     * @param passwd  密码
     */
    public void updatePasswd(String number,int type,String passwd){
        SysUser user = null;
        if (type == 1){

        }else if(type == 2){
            user = sysUserDao.get("email", number);
            user.setPassword(PasswordUtils.encode(passwd));
        }
        sysUserDao.update(user);
    }
}
